/**************** CONFIGURACIÓN ****************/

const FOLDER_INGRESOS_ID = "1fBlgTF8Nc8Op3iPWQ0aHr76W6tPQ1nj9";
const SHEET_NAME_REGISTRO = "Registro";

const DESTINOS_CARPETAS = {
  "Obras": "1kaZ318Bzy6pcNICvDlgg3BEB01u6VZde",
  "Habilitaciones": "1umoerbNX_L7dL6Y6sMO5_X3Y-UJAH9OC",
  "Salud": "1n_aD-1tMnv7Bu1yQHA7-435C1Y-rPTLi",
  "Desarrollo Social": "1rAttqXMnoN8zNBHE1vHo6KN3PTIEp9_A",
  "Otros": "1HpsV-1KB0CO450eIRGt2jFqlBsfEGXDJ"
};

/**************** PROCESO PRINCIPAL ****************/

function procesarDriveIngresos() {

  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = getOrCreateSheet_(ss, SHEET_NAME_REGISTRO);
  ensureHeaderRegistro_(sheet);

  const folderIngresos = DriveApp.getFolderById(FOLDER_INGRESOS_ID);
  const files = folderIngresos.getFiles();

  const fechaDerivacion = new Date();
  const tz = Session.getScriptTimeZone();

  while (files.hasNext()) {

    const file = files.next();
    const fileId = file.getId();
    const nombreOriginal = file.getName();
    const mime = file.getMimeType();
    const fechaIngreso = file.getDateCreated ? file.getDateCreated() : "";

    let texto = "";
    let datos = null;
    let error = "";

    // Solo leemos texto si es Google Docs
    if (mime === MimeType.GOOGLE_DOCS) {
      try {
        texto = DocumentApp.openById(fileId).getBody().getText().slice(0, 12000);
      } catch (e) {
        texto = "";
      }
    }

    // 1) Clasificación por nombre
    datos = clasificarPorNombre_(nombreOriginal);

    // 2) Si hay texto real, intentamos IA
    if (texto) {
      try {
        datos = clasificarYExtraerOpenAI_(nombreOriginal, mime, texto);
      } catch (e) {
        error = e.message || String(e);
      }
    }

    const tema = datos.tema || "Otros";
    const destFolderId = DESTINOS_CARPETAS[tema] || DESTINOS_CARPETAS["Otros"];
    const destFolder = DriveApp.getFolderById(destFolderId);

    const firmante = datos.firmante_apellido_nombre || "";
    let organizacion = datos.organizacion || "";
    if (!organizacion) organizacion = firmante;

    const fechaNombre = Utilities.formatDate(fechaDerivacion, tz, "yyyy-MM-dd");
    const nombreNuevo = `${fechaNombre}_${tema}_${limpiar_(nombreOriginal)}`;

    file.setName(nombreNuevo);
    destFolder.addFile(file);
    folderIngresos.removeFile(file);

    sheet.appendRow([
      fechaIngreso,
      fechaDerivacion,
      tema,
      firmante,
      organizacion,
      fileId,
      nombreOriginal,
      nombreNuevo,
      mime,
      datos.confianza || "",
      datos.urgencia || "",
      datos.resumen_1_linea || "",
      texto ? "TextoOK" : "SinTexto",
      error
    ]);
  }
}

/**************** CLASIFICACIÓN POR REGLAS ****************/

function clasificarPorNombre_(nombreArchivo) {

  const n = String(nombreArchivo || "").toLowerCase();

  // SALUD directo
  if (contieneAlguna_(n, ["salud", "hospital", "vacuna", "medico", "médico"])) {
    return baseRespuesta_("Salud", "Documento vinculado a salud pública", "alta");
  }

  // ANIMALES prioridad Salud
  if (n.includes("animal") || n.includes("perro")) {
    if (contieneAlguna_(n, ["asistencia", "refugio", "comunit", "proteccionista", "barrio"])) {
      return baseRespuesta_("Desarrollo Social", "Problemática social vinculada a animales", "media");
    }
    return baseRespuesta_("Salud", "Documento vinculado a animales con impacto sanitario", "alta");
  }

  // OBRAS
  if (contieneAlguna_(n, ["bache", "bacheo", "vereda", "asfalto", "pavimento", "obra", "calle"])) {
    return baseRespuesta_("Obras", "Documento vinculado a obras públicas", "alta");
  }

  // HABILITACIONES
  if (contieneAlguna_(n, ["habilit", "permiso", "comercio", "clausura", "inspeccion"])) {
    return baseRespuesta_("Habilitaciones", "Documento vinculado a habilitaciones", "alta");
  }

  // DESARROLLO SOCIAL
  if (contieneAlguna_(n, ["social", "subsidio", "familia", "asistencia", "vulner"])) {
    return baseRespuesta_("Desarrollo Social", "Documento vinculado a asistencia social", "media");
  }

  return baseRespuesta_("Otros", "Sin señal suficiente en el nombre", "baja");
}

function baseRespuesta_(tema, resumen, confianza) {
  return {
    tema: tema,
    resumen_1_linea: resumen,
    urgencia: "Media",
    confianza: confianza,
    firmante_apellido_nombre: "",
    organizacion: ""
  };
}

function contieneAlguna_(texto, arr) {
  for (let i = 0; i < arr.length; i++) {
    if (texto.indexOf(arr[i]) !== -1) return true;
  }
  return false;
}

/**************** CLASIFICACIÓN CON OPENAI ****************/

function clasificarYExtraerOpenAI_(nombreArchivo, mimeType, text) {

  const apiKey = PropertiesService.getScriptProperties().getProperty("OPENAI_API_KEY");
  if (!apiKey) throw new Error("Falta OPENAI_API_KEY");

  const schema = {
    type: "object",
    additionalProperties: false,
    required: ["tema", "resumen_1_linea", "urgencia", "confianza", "firmante_apellido_nombre", "organizacion"],
    properties: {
      tema: { type: "string", enum: ["Obras", "Habilitaciones", "Salud", "Desarrollo Social", "Otros"] },
      resumen_1_linea: { type: "string" },
      urgencia: { type: "string", enum: ["Alta", "Media", "Baja"] },
      confianza: { type: "string", enum: ["alta", "media", "baja"] },
      firmante_apellido_nombre: { type: "string" },
      organizacion: { type: "string" }
    }
  };

  const payload = {
    model: "gpt-4.1-mini",
    store: false,
    input: [
      { role: "system", content: "Clasificás documentos municipales. No inventás datos." },
      { role: "user", content: `Nombre: ${nombreArchivo}\n\nContenido:\n${text}` }
    ],
    text: {
      format: {
        type: "json_schema",
        name: "clasificacion",
        schema: schema,
        strict: true
      }
    }
  };

  const res = UrlFetchApp.fetch("https://api.openai.com/v1/responses", {
    method: "post",
    contentType: "application/json",
    headers: { Authorization: "Bearer " + apiKey },
    payload: JSON.stringify(payload)
  });

  const json = JSON.parse(res.getContentText());
  const out = extractOutputText_(json);
  return JSON.parse(out);
}

/**************** UTILIDADES ****************/

function getOrCreateSheet_(ss, name) {
  let sh = ss.getSheetByName(name);
  if (!sh) sh = ss.insertSheet(name);
  return sh;
}

function ensureHeaderRegistro_(sheet) {
  const header = [
    "Fecha de ingreso",
    "Fecha de derivación",
    "Tema",
    "Apellido y nombre",
    "Organización",
    "FileId",
    "Nombre original",
    "Nombre nuevo",
    "MIME",
    "Confianza",
    "Urgencia",
    "Resumen",
    "Texto",
    "Error"
  ];
  if (sheet.getLastRow() === 0) {
    sheet.getRange(1, 1, 1, header.length).setValues([header]);
  }
}

function limpiar_(s) {
  return (s || "").replace(/[^\w\s.-]/g, "_").slice(0, 80);
}

function extractOutputText_(respJson) {
  const output = respJson.output || [];
  for (let i = 0; i < output.length; i++) {
    const item = output[i];
    if (item.type === "message") {
      for (let j = 0; j < item.content.length; j++) {
        if (item.content[j].text) return item.content[j].text;
      }
    }
  }
  throw new Error("No se encontró output_text");
}
